package com.example.huadu_server.config;


import cn.dev33.satoken.exception.NotLoginException;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 捕获校验失败异常( DTO )
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) {
            errors.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return new Response<>(400, "参数校验失败", errors);
    }


    /**
     * 捕获 Sa-Token 的 NotLoginException
     */
    @ExceptionHandler(NotLoginException.class)
    public ResponseEntity<Response<String>> handleNotLoginException(NotLoginException e) {
        // 根据异常的类型返回不同的提示信息
        String message;
        switch (e.getType()) {
            case NotLoginException.NOT_TOKEN:
                message = "未提供 Token";
                break;
            case NotLoginException.INVALID_TOKEN:
                message = "Token 无效";
                break;
            case NotLoginException.TOKEN_TIMEOUT:
                message = "Token 已过期";
                break;
            case NotLoginException.BE_REPLACED:
                message = "Token 被顶下线";
                break;
            case NotLoginException.KICK_OUT:
                message = "Token 已被踢下线";
                break;
            default:
                message = "未登录";
        }
        return ResponseEntity.status(401).body(new Response<>(401, message, null));
    }
}
